helloApp.config(function($stateProvider) {

    $stateProvider
    .state('root.admin.users.new', {
        url: "/user/new",
        views: {
            "usersView@root.admin.users": {
                templateUrl : "/app/private/user/view/user_edit.html",
                controller: "UserEditCtrl"
            },
            "hobbiesView@root.admin.users.new": {
                 templateUrl: "/app/private/hobby/view/hobbies_edit.html",
                 controller: "HobbiesEditCtrl"
            }
        }
    })
    .state('root.admin.users.edit', {
        url: "/user/edit/:id",
        views: {
            "usersView@root.admin.users": {
                templateUrl : "/app/private/user/view/user_edit.html",
                controller: "UserEditCtrl"
            },
            "hobbiesView@root.admin.users.edit": {
                templateUrl: "/app/private/hobby/view/hobbies_edit.html",
                controller: "HobbiesEditCtrl"
            }
        }
    });
});

helloApp.controller('UserEditCtrl', function ($scope, $http, $stateParams, $state, UserService, HobbyService) {

    var id_user = Number($stateParams.id);

    $scope.formUser = {};

    $scope.hobbies = [];

    $scope.$flow.cancel();

    $scope.formUser.image = null;

    // if it's a new user
    if (!_.isNaN(id_user) && (id_user > -1)) {

		UserService.getById(id_user, function(data) {
			$scope.formUser = data;
		});

		HobbyService.getHobbiesByUser(id_user, function(data) {
            $scope.hobbies = data;
        });

		$scope.saveOrUpdateUser = function () {

			UserService.update(this.formUser, function(data) {

			    HobbyService.updateList(data.id, $scope.hobbies, function(data) {
                    $state.go('root.admin.users', null, {reload:true});
                });
			});
		};

    } else {

    	$scope.saveOrUpdateUser = function () {

			UserService.save(this.formUser, function(data) {

			    //UserService.uploadImage(image, function (data) {

                    HobbyService.saveList(data.id, $scope.hobbies, function(data) {
                        $state.go('root.admin.users', null, {reload:true});
                    });
                //});
			});
		};
    }

    $scope.$flow.onUploaded = function(img) {
        $scope.formUser.image = angular.fromJson(img);
    }
});